import axios from 'axios'
import {Message, MessageBox} from 'iview'
import env from '../../build/env';
import store from '@/store'
import {getToken} from '../libs/auth'


const ajaxUrl = env === 'development'
    ? 'http://127.0.0.1:9988/admin'
    : env === 'production'
        ? 'https://www.url.com'
        : 'https://debug.url.com';


// 创建一个 axios 实例
const service = axios.create({
    baseURL: ajaxUrl, // api的base_url
    timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
    // Do something before request is sent
    if (store.getters.token) {
        config.headers['Admin-Token'] = getToken() // 让每个请求携带token-- ['Admin-Token']为自定义key 请根据实际情况自行修改
    }
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.errno === 501) {
            MessageBox.alert('系统未登录，请重新登录', '未登录', {
                confirmButtonText: '确定',
                type: 'error'
            }).then(() => {
                store.dispatch('logout').then(() => {
                    location.reload()
                })
            })
            return Promise.reject('error')
        } else if (res.errno === 502) {
            MessageBox.alert('系统内部错误，请联系管理员维护', '错误', {
                confirmButtonText: '确定',
                type: 'error'
            })
            return Promise.reject('error')
        } else if (res.errno === 503) {
            MessageBox.alert('请求业务目前未支持', '警告', {
                confirmButtonText: '确定',
                type: 'error'
            })
            return Promise.reject('error')
        } else if (res.errno !== 0) {
            // 非5xx的错误属于业务错误，留给具体页面处理
            return Promise.reject(response)
        } else {
            return response
        }
    }, error => {
        console.log('err' + error)// for debug
        Message({
            message: '登录连接超时（后台不能连接，请联系系统管理员）',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    })

export default service
